<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
    :error="error"
    error-text="加载失败，请重试"
    :immediate-check="false"
  >
    <commentItem
      @response="$emit('isreplayShow', $event)"
      v-for="(item, index) in list"
      :key="index"
      :comment="item"
    />
  </van-list>
</template>
<script>
import { getComments } from '@/api/comment'
import commentItem from '@/components/comment-item'
export default {
  name: 'comment',

  props: {
    articleId: {
      required: true
    },
    list: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      validator(val) {
        return ['a', 'c'].includes(val)
      },
      default: 'a'
    }
  },
  created() {
    this.loading = true
    this.onLoad()
  },
  components: { commentItem },
  computed: {},
  data() {
    return {
      loading: false,
      finished: false,
      offset: null,
      totalCount: 0,
      error: false
    }
  },
  methods: {
    async onLoad() {
      // 1. 请求获取数据
      try {
        const { data } = await getComments({
          type: this.type, // 评论类型，a-对文章(article)的评论，c-对评论(comment)的回复
          source: this.articleId.toString(), // 源id，文章id或评论id
          offset: this.offset, // 获取评论数据的偏移量，值为评论id，表示从此id的数据向后取，不传表示从第一页开始读取数据
          limit: 10 // 每页大小
        })

        // 2. 将数据添加到列表中
        const { results } = data.data
        this.list.push(...results)
        console.log(this.list)
        this.$emit('onload', data.data)

        // 更新总数据条数
        this.totalCount = data.data.total_count

        // 3. 将加载更多的 loading 设置为 false
        this.loading = false

        // 4. 判断是否还有数据
        if (results.length) {
          this.offset = data.data.last_id // 更新获取下一页数据的页码
        } else {
          this.finished = true // 没有数据了，关闭加载更多
        }
      } catch (error) {
        console.dir(error)
        this.error = true
        this.loading = false
      }
    }
  }
}
</script>
<style lang="less" scoped></style>
